package cn.dapeng.tree.binary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树按层遍历
 */
public class WalkThroughLevelTree {

    public static LinkedList<List<Integer>> walkThough(TreeNode head) {

        if (head == null) {
            return null;
        }

        LinkedList<List<Integer>> ans = new LinkedList<>();
        List<Integer> l = new ArrayList<>(1);
        l.add(head.val);

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(head);
        while (!queue.isEmpty()) {

            int size = queue.size();
            List<Integer> curAns = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                curAns.add(0, node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            ans.add(0, curAns);
        }

        return ans;

    }

    public static void main(String[] args) {
        TreeNode head = new TreeNode(0);
        head.left = new TreeNode(1);
        head.right = new TreeNode(1);

        head.left.left = new TreeNode(2);
        head.right.right = new TreeNode(2);

        head.left.right = new TreeNode(3);
        head.right.left = new TreeNode(3);

        LinkedList<List<Integer>> ans = walkThough(head);

        for(List<Integer> list : ans) {
            for (Integer n : list) {
                System.out.print(n + ",");
            }
            System.out.println();
        }
    }



}
